<template>
	<view>
		<view class="auth">
			<view class="wanl-title">欢迎绑定手机号</view>
			
			<form @submit="formSubmit">
				<view class="auth-group radius-bock bg-gray wlian-grey-light">
					<input 
						placeholder="请输入手机号" 
						type="number" maxlength="11" 
						placeholder-class="placeholder" 
						name="mobile"
						v-model="mobile"
					></input>
				</view>
				
				<view class="auth-group flex justify-between radius-bock bg-gray wlian-grey-light">
					<input 
						placeholder="请输入验证码" 
						type="number" 
						maxlength="6" 
						placeholder-class="placeholder"
						v-model="code"
					></input>
					
					<view @click="onGetCode">{{codeTips}}</view>
				</view>
				
				<view class="auth-button flex flex-direction">
					<button class="cu-btn bg-orange sl radius-bock" form-type="submit">绑定</button><!-- disabled="true" -->
				</view>
			</form>
		</view>
	</view>
</template>

<script>
	import graceChecker from '@/common/graceChecker';
	export default {
		data() {
			return {
				mobile: "", //手机号
				code: "", //验证码
				
				countdownInterval: null,
				countTime: 60,
				codeTips: "获取验证码",
			}
		},
		onUnload() {
			clearInterval(this.countdownInterval);
		},
		methods: {
			/**
			 * 获取验证码
			 */
			onGetCode() {
				if (this.mobile === "") {
					this.$wanlshop.msg('请输入手机号');
					return
				}
				uni.request({
				    url: '/wanlshop/sms/send', 
					method: 'POST',
					data:{
						event: "changemobile",  
						mobile: this.mobile
					},
				    success: res => {
						this.$wanlshop.msg('验证码发送成功');
						this.startCountdown();
				    },
				});
			},
			/**
			 * 倒计时
			 */
			startCountdown() {
				this.countTime = 60;
				this.countdownInterval = setInterval(() => {
					if (this.countTime > 0) {
						this.countTime--;
						this.codeTips = this.countTime + "s后获取";
					} else {
						clearInterval(this.countdownInterval);
						this.codeTips = "获取验证码";
					}
				}, 1000);
			},
			/**
			 * 验证
			 */
			formSubmit() {
				if (this.mobile === "") {
					this.$wanlshop.msg('请输入手机号');
					return
				}
				if (this.code === "") {
					this.$wanlshop.msg('请输入验证码');
					return
				}
				let pageroute = this.getUrlCode().state; // 截取state
				uni.request({
				    url: '/wanlshop/user/changemobile', 
					method: 'POST',
					data:{
						mobile: this.mobile,
						captcha: this.code
					},
				    success: res => {
						// 返回页面
						uni.switchTab({
							url:'/pages/user'
						});
				    },
				});
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import url("auth.css");
</style>